import os
import time

from flask import Response, Flask
from prometheus_client import CollectorRegistry, Gauge, generate_latest

app = Flask(__name__)

# 定义数据仓库
REGISTRY = CollectorRegistry()

file_updated_time = Gauge('file_updated_time', 'file_updated_time', ['exporter_name', 'host_ip', 'file_name'],
                          registry=REGISTRY)


def get_file_updated_time(file_list: list() = [], host_ip: str() = 'localhost'):
    for check_file in file_list:
        try:
            diff_time = time.time() - os.path.getmtime(check_file)
            file_updated_time.labels(exporter_name='check_file_exporter', host_ip=host_ip, file_name=check_file).set(
                int(diff_time))
        except Exception as e:
            print("有异常:", e)
            pass


# 字符串转换成数组并返回
def get_list_from_str(file_names: str = './main.py') -> list():
    return file_names.split(',')


@app.route("/metrics")
def api_response():
    file_names = os.getenv("CHECK_FILE_EXPORTER_FILE_NAMES")
    host_ip = os.getenv("CHECK_FILE_EXPORTER_HOST_IP")

    get_file_updated_time(file_list=get_list_from_str(file_names), host_ip=host_ip)
    return Response(generate_latest(REGISTRY), mimetype="text/plain")


@app.route('/health')
def index():
    return "CHECK_FILE_EXPORTER metrics"


# powershell 设置环境变量
# $env:CHECK_FILE_EXPORTER_FILE_NAMES="./test.py,./README2.md"
# $env:CHECK_FILE_EXPORTER_HOST_IP="1.3.4.1"

# linux 设置环境变量:
# export CHECK_FILE_EXPORTER_FILE_NAMES="./test.py,./README2.md"
# export CHECK_FILE_EXPORTER_HOST_IP="1.3.4.1"

# gunicorn --workers=1 main:app -b 0.0.0.0:8000
if __name__ == "__main__":
    os.environ['CHECK_FILE_EXPORTER_FILE_NAMES'] = "./test.py,./README.md,./main.py"
    os.environ['CHECK_FILE_EXPORTER_HOST_IP'] = ".10.32.48.10"
    app.run(host='0.0.0.0', port=8000, debug=True)
